package com.xiaotao.consumer;

import com.rabbitmq.client.Channel;
import com.xiaotao.entity.Orders;
import com.xiaotao.mapper.CouponMapper;
import com.xiaotao.mapper.OrdersMapper;
import com.xiaotao.service.OrderService;
import com.xiaotao.service.WebSocketPushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

import static com.xiaotao.config.RabbitConfig.QUEUE_CHECK_ORDER_STATUS;

@Component
@Slf4j
public class CheckOrderConsumer {
    @Resource
    private OrderService orderService;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private CouponMapper couponMapper;
    @Resource
    private WebSocketPushService wsPush;

    /**
     * 延迟队列监听
     */
    @RabbitListener(queues =QUEUE_CHECK_ORDER_STATUS)
    @Transactional
    public void consume(String id, Channel channel, Message message)
    {
        try
        {
            log.info("延迟队列收到订单消息: {}", id);


            Orders orders = ordersMapper.selectByPrimaryKey(id);
            if (orders == null) {
                throw new RuntimeException("订单不存在");
            }
            // 幂等：已取消或已支付跳过
            if (orders.getStatus() != 0) {
                return;
            }

            // 更新状态：2 = 已取消
            orders.setStatus((byte)2);
            orders.setCancelTime(new Date());
            ordersMapper.updateByPrimaryKeySelective(orders);

            // 退回优惠券
            if (orders.getCouponId() != null) {
                couponMapper.updateStatus(orders.getCouponId(), 0);
            }
            wsPush.sendOrderMsg(orders.getUserId(), "订单取消"+orders.getId());

            log.info("订单 {} 已自动取消", id);


            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        }
        catch
        (Exception e) {
            log.error("处理订单 {} 异常", id,e);
            try {
                // 重回队列或死信
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            }
            catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
